package com.bbjob.service.impl;

import java.io.File;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.bbjob.client.result.ResultForDeliveryExamInfo;
import com.bbjob.client.result.ResultForDeliveryQuestionBank;
import com.bbjob.client.result.ResultForDeliverySysOrganization;
import com.bbjob.client.result.ResultForExamInfo;
import com.bbjob.client.result.ResultForExamineeList;
import com.bbjob.client.result.ResultForQuestionBankList;
import com.bbjob.dto.Result;
import com.bbjob.mapper.DeliveryExamInfoMapper;
import com.bbjob.mapper.DeliveryExamineeInfoMapper;
import com.bbjob.mapper.DeliveryExamineeScoresDetailMapper;
import com.bbjob.mapper.DeliveryExamineeScoresMapper;
import com.bbjob.mapper.DeliveryQuestionBankMapper;
import com.bbjob.mapper.DeliverySysOrganizationMapper;
import com.bbjob.model.DeliveryExamInfo;
import com.bbjob.model.DeliveryExamineeInfo;
import com.bbjob.model.DeliveryExamineeScores;
import com.bbjob.model.DeliveryExamineeScoresDetail;
import com.bbjob.model.DeliveryQuestionBank;
import com.bbjob.model.DeliverySysOrganization;
import com.bbjob.model.ExamInfo;
import com.bbjob.model.ExamineeScores;
import com.bbjob.model.QuestionBank;
import com.bbjob.query.QueryExamInfo;
import com.bbjob.service.IExamInfoService;
import com.bbjob.service.ISystemService;
import com.bbjob.toolutil.HttpClientUtil;
import com.bbjob.toolutil.Tool;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

@Service
public class ExamInfoServiceImpl implements IExamInfoService {

	@Value("${sys.uniquecode}")
	private String uniquecode;
	@Value("${examol.center.url}")
	private String centerUrl;
	@Value("${examol.center.exam.entry}")
	private String centerExamEntry;
	@Value("${examol.center.exam.entryFull}")
	private String centerExamEntryFull;
	@Value("${examol.center.exam.list}")
	private String centerExamList;
	@Value("${examol.center.exam.item}")
	private String centerExamItem;
	@Value("${examol.center.exam.edit}")
	private String centerExamEdit;
	@Value("${examol.center.exam.del}")
	private String centerExamDel;
	@Value("${sys.local.exam.file.path}")
	private String examLocalFileDir;
	@Value("${examol.center.exam.import}")
	private String centerExamImport;
	@Value("${examol.center.exam.paper}")
	private String centerExamPaper;
	@Value("${examol.center.stuAll}")
	private String centerExamineeAll;
	@Value("${examol.center.exam.paper.all}")
	private String centerExamPaperAll;
	@Value("${oss.accessKeyId}")
	private String accessKeyId;
	@Value("${oss.accessKeySecret}")
	private String accessKeySecret;
	@Value("${oss.endpoint}")
	private String endpoint;
	@Value("${oss.bucket}")
	private String bucket;
	@Value("${sys.local.exam.paper.path}")
	private String paperPath;
	@Value("${examol.center.sys.organInfo.url}")
	private String centerSysOrganInfoUrl;
	@Resource
	private DeliveryExamineeInfoMapper deliveryExamineeInfoMapper;
	@Resource
	private DeliveryExamInfoMapper deliveryExamInfoMapper;
	@Resource
	private DeliveryQuestionBankMapper deliveryQuestionBankMapper;
	@Resource
	private DeliverySysOrganizationMapper deliverySysOrganizationMapper;
	@Resource
	private DeliveryExamineeScoresMapper deliveryExamineeScoresMapper;
	@Resource
	private DeliveryExamineeScoresDetailMapper deliveryExamineeScoresDetailMapper;
	@Resource
	private ExamineeScoresService examineeScoresService;
	@Resource
	private ExamineeScoresDetailService examineeScoresDetailService;
	@Resource
	private ISystemService systemService;
	@Resource
	private AsyncTask asyncTask;
	
	@Override
	public ExamInfo entryInfo(ExamInfo exam) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// SimpleDateFormat sdfDir = new SimpleDateFormat("yyyyMMdd");
		
		try {
/*			String saveDirectory = "";
			if (multipartFile != null && !multipartFile.isEmpty()) {
				saveDirectory = examLocalFileDir + uniquecode +"/" + sdfDir.format(new Date()) + "/" + multipartFile.getOriginalFilename();
				File path = new File(saveDirectory);
				
				if (!path.getParentFile().exists()) {
					path.getParentFile().mkdirs();
					path.createNewFile();
				}
				
				multipartFile.transferTo(path);
				params.put("filename", multipartFile.getOriginalFilename());
			}*/
									
			params.put("uniquecode", uniquecode);
			
			if (exam.geteName() != null && !"".equals(exam.geteName())) {
				params.put("eName", exam.geteName());
			}
/*			if (request.getParameter("eName") != null && !"".equals(request.getParameter("eName"))) {
				params.put("eName", request.getParameter("eName"));
			}*/
			
			if (exam.geteClassify() != null && !"".equals(exam.geteClassify())) {
				params.put("eClassify", exam.geteClassify());
			}
/*			if (request.getParameter("eClassify") != null && !"".equals(request.getParameter("eClassify"))) {
				params.put("eClassify", request.getParameter("eClassify"));
			}*/
			
			if (exam.geteStarttime() != null) {
				params.put("eStarttimeStr", sdf.format(exam.geteStarttime()));
			}
/*			if (request.getParameter("eStarttimeStr") != null && !"".equals(request.getParameter("eStarttimeStr"))) {
				params.put("eStarttimeStr", sdf.format(request.getParameter("eStarttimeStr")));
			}*/
			
			if (exam.geteEndtime() != null) {
				params.put("eEndtimeStr", sdf.format(exam.geteEndtime()));
			}
/*			if (request.getParameter("eEndtimeStr") != null && !"".equals(request.getParameter("eEndtimeStr"))) {
				params.put("eEndtimeStr", sdf.format(request.getParameter("eEndtimeStr")));
			}*/
			if (exam.geteStarttime() != null && exam.geteEndtime() != null) {
				exam.seteTimeLength(Tool.subDateMine(exam.geteStarttime(), exam.geteEndtime()));
			}
			
			if (exam.geteTimeLength() != null) {
				params.put("eTimeLength", exam.geteTimeLength());
			}
/*			if (request.getParameter("eTimeLength") != null && !"".equals(request.getParameter("eTimeLength"))) {
				params.put("eTimeLength", request.getParameter("eTimeLength"));
			}*/
			
			if (exam.getPassingGrade() != null) {
				params.put("passingGrade", exam.getPassingGrade());
			}
/*			if (request.getParameter("passingGrade") != null && !"".equals(request.getParameter("passingGrade"))) {
				params.put("passingGrade", request.getParameter("passingGrade"));
			}*/
			
			if (exam.getAnswerNumber() != null) {
				params.put("answerNumber", exam.getAnswerNumber());
			}
/*			if (request.getParameter("answerNumber") != null && !"".equals(request.getParameter("answerNumber"))) {
				params.put("answerNumber", request.getParameter("answerNumber"));
			}*/
			
			if (exam.geteMode() != null && !"".equals(exam.geteMode())) {
				params.put("eMode", exam.geteMode());
			}
/*			if (request.getParameter("eMode") != null && !"".equals(request.getParameter("eMode"))) {
				params.put("eMode", request.getParameter("eMode"));
			}*/
			
			if (exam.getStatus() != null) {
				params.put("status", exam.getStatus());
			}
/*			if (request.getParameter("status") != null && !"".equals(request.getParameter("status"))) {
				params.put("status", request.getParameter("status"));
			}*/
			
			if (exam.getRemark() != null && !"".equals(exam.getRemark())) {
				params.put("remark", exam.getRemark());
			}
/*			if (request.getParameter("remark") != null && !"".equals(request.getParameter("remark"))) {
				params.put("remark", request.getParameter("remark"));
			}*/
			
			if (exam.getqId() != null && !"".equals(exam.getqId())) {
				params.put("qId", exam.getqId());
			}
/*			if (request.getParameter("qId") != null && !"".equals(request.getParameter("qId"))) {
				params.put("qId", request.getParameter("qId"));
			}*/
			
			if (exam.getField1() != null && !"".equals(exam.getField1())) {
				params.put("field1", exam.getField1());
			}
			
			if (exam.getField2() != null && !"".equals(exam.getField2())) {
				params.put("field2", exam.getField2());
			}
			
			if (exam.getField3() != null && !"".equals(exam.getField3())) {
				params.put("field3", exam.getField3());
			}
			
			if (exam.getField4() != null) {
				params.put("field4", exam.getField4());
			}
			
			String resultStr = "";
			
/*			if (multipartFile != null && !multipartFile.isEmpty()) {
				// resultStr = HttpClientUtil.doPost();
				saveDirectory = examLocalFileDir + uniquecode +"/" + sdfDir.format(new Date()) + "/" + multipartFile.getOriginalFilename();
				File path = new File(saveDirectory);
				resultStr = HttpClientUtil.doPost(centerUrl + centerExamEntryFull, path, params);
			} else {*/
				
			resultStr = HttpClientUtil.doPost(centerUrl + centerExamEntry, params);
			// }
			
		    GsonBuilder builder = new GsonBuilder();
		    
		    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
			
			ResultForExamInfo result = builder.create().fromJson(resultStr, ResultForExamInfo.class);
			
			if (result.getCode() == 200) {
				
				downloadQueBankFromCenter(result.getData().getId());	
				
				return result.getData();
			} else {
				
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	@Override
	public Result selectByParams(QueryExamInfo exam) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		try {
			Result testConn = systemService.TestConn();
			if (testConn.getCode() == 200) {
				params.put("uniquecode", uniquecode);
				params.put("pageNum", exam.getPageNum());
				params.put("pageSize", exam.getPageSize());
				
				if (exam.getEname() != null && !"".equals(exam.getEname())) {
					params.put("ename", exam.getEname());
				}
				
				if (exam.getStatus() != null) {
					params.put("status", exam.getStatus());
				}
				
				String resultStr = HttpClientUtil.doPost(centerUrl + centerExamList, params);
				
				Result list = new Gson().fromJson(resultStr, Result.class);
				
				return list;
			} else {
				
				List<DeliveryExamInfo> all = deliveryExamInfoMapper.selectAll();
				
				if (exam.getPageNum() == 0) {
					exam.setPageNum(1);
				}
				
				if (exam.getPageSize() == 0) {
					exam.setPageSize(10);
				}
				
				exam.setPageNum((exam.getPageNum() - 1) * exam.getPageSize());
				List<DeliveryExamInfo> list = deliveryExamInfoMapper.selectByParams(exam);
				
				for (DeliveryExamInfo deliveryExamInfo : list) {
					DeliveryExamineeInfo deliveryExamineeInfo = new DeliveryExamineeInfo();
					deliveryExamineeInfo.seteId(deliveryExamInfo.getId());
					List<DeliveryExamineeInfo> examineeInfos = deliveryExamineeInfoMapper.selectByParams(deliveryExamineeInfo);
					
					deliveryExamInfo.setTestNum(examineeInfos.size());
					deliveryExamInfo.setServerTime(new Date());
				}
				
				Map<String, Object> returnMap = new HashMap<String, Object>();
				returnMap.put("pageNum", exam.getPageNum());
				returnMap.put("pageSize", exam.getPageSize());
				returnMap.put("total", all.size());
				returnMap.put("list", list);
				
				return new Result(returnMap);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public Result selectByPrimaryKey(Integer id) {
		
		try {
			Result testConn = systemService.TestConn();
			if (testConn.getCode() == 200) {
				String resultStr = HttpClientUtil.doGet(centerUrl + centerExamItem + id);
				
			    GsonBuilder builder = new GsonBuilder();
			    
			    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
			    	@Override   
			    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
			    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
			    	}
			    });
			    
			    Result result = builder.create().fromJson(resultStr, Result.class);
			
				return result;
			} else {
				DeliveryExamInfo examInfo = deliveryExamInfoMapper.selectByPrimaryKey(id);
				
				examInfo.setServerTime(new Date());
				
				return new Result(examInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public void updateStudent(ExamInfo exam, Integer id) {
		Map<String, Object> params = new HashMap<String, Object>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {

			params.put("uniquecode", uniquecode);
			
			if (exam.geteName() != null && !"".equals(exam.geteName())) {
				params.put("eName", exam.geteName());
			}
			
			if (exam.geteClassify() != null && !"".equals(exam.geteClassify())) {
				params.put("eClassify", exam.geteClassify());
			}
			
			if (exam.geteStarttime() != null) {
				params.put("eStarttimeStr", sdf.format(exam.geteStarttime()));
			}
/*			if (request.getParameter("eStarttimeStr") != null && !"".equals(request.getParameter("eStarttimeStr"))) {
				params.put("eStarttimeStr", sdf.format(request.getParameter("eStarttimeStr")));
			}*/
			
			if (exam.geteEndtime() != null) {
				params.put("eEndtimeStr", sdf.format(exam.geteEndtime()));
			}
/*			if (request.getParameter("eEndtimeStr") != null && !"".equals(request.getParameter("eEndtimeStr"))) {
				params.put("eEndtimeStr", sdf.format(request.getParameter("eEndtimeStr")));
			}*/
			
			if (exam.geteStarttime() != null && exam.geteEndtime() != null) {
				exam.seteTimeLength(Tool.subDateMine(exam.geteStarttime(), exam.geteEndtime()));
			}
			
			if (exam.geteTimeLength() != null) {
				params.put("eTimeLength", exam.geteTimeLength());
			}
			
			if (exam.getPassingGrade() != null) {
				params.put("passingGrade", exam.getPassingGrade());
			}
			
			if (exam.getAnswerNumber() != null) {
				params.put("answerNumber", exam.getAnswerNumber());
			}
			
			if (exam.geteMode() != null && !"".equals(exam.geteMode())) {
				params.put("eMode", exam.geteMode());
			}
			
			if (exam.getStatus() != null) {
				params.put("status", exam.getStatus());
			}
			
			if (exam.getRemark() != null && !"".equals(exam.getRemark())) {
				params.put("remark", exam.getRemark());
			}
			
			if (exam.getqId() != null && !"".equals(exam.getqId())) {
				params.put("qId", exam.getqId());
			}
			
			if (exam.getField1() != null && !"".equals(exam.getField1())) {
				params.put("field1", exam.getField1());
			}
			
			if (exam.getField2() != null && !"".equals(exam.getField2())) {
				params.put("field2", exam.getField2());
			}
			
			if (exam.getField3() != null && !"".equals(exam.getField3())) {
				params.put("field3", exam.getField3());
			}
			
			if (exam.getField4() != null) {
				params.put("field4", exam.getField4());
			}
			
			
			String resultStr = HttpClientUtil.doPost(centerUrl + centerExamEdit + id, params);
			
			downloadQueBankFromCenter(id);	
			System.out.println(resultStr);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delById(Integer id) {
		try {
			String resultStr = HttpClientUtil.doGet(centerUrl + centerExamDel + id);
			
			System.out.println(resultStr);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Map<String, Object> importExaminee(MultipartFile multipartFile,
			HttpServletRequest request) {
		
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		
		if (multipartFile == null || multipartFile.isEmpty()) {
			
			returnMap.put("code", 500);
			returnMap.put("message", "文件为空");
			returnMap.put("data", null);
			return returnMap;
		}
		
		String eId = "";
		if (request.getParameter("eId") != null && !"".equals(request.getParameter("eId"))) {
			eId = request.getParameter("eId");
		} else {
			returnMap.put("code", 500);
			returnMap.put("message", "未选中一场考试");
			returnMap.put("data", null);
			return returnMap;
		}
		

		String saveDirectory = examLocalFileDir + uniquecode +"/" + sdf.format(new Date()) + "/" + multipartFile.getOriginalFilename();
		
		try {
			File path = new File(saveDirectory);
			
			if (!path.getParentFile().exists()) {
				path.getParentFile().mkdirs();
				path.createNewFile();
			}
			
			multipartFile.transferTo(path);
			
			Map<String, Object> params = new HashMap<String, Object>();
			
			params.put("uniquecode", uniquecode);
			params.put("filename", multipartFile.getOriginalFilename());
			params.put("eId", eId);
			
			String result = HttpClientUtil.doPost(centerUrl + centerExamImport, path, params);
			
		    GsonBuilder builder = new GsonBuilder();
		    
		    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
			
			returnMap = builder.create().fromJson(result, HashMap.class);
			
			// 同步考生信息
			params.put("id", eId);
			params.put("uniquecode", uniquecode);
			String examineeStr = HttpClientUtil.doPost(centerUrl + centerExamineeAll, params);
			
			ResultForExamineeList examinees = builder.create().fromJson(examineeStr, ResultForExamineeList.class);
			
			if (examinees.getCode() == 200) {
				List<DeliveryExamineeInfo> list = examinees.getData();
				for (DeliveryExamineeInfo info : list) {
					DeliveryExamineeInfo examineeInfo = deliveryExamineeInfoMapper.selectByPrimaryKey(info.getId());
					if (examineeInfo != null) {
						deliveryExamineeInfoMapper.updateByPrimaryKey(examineeInfo);
					} else {
						deliveryExamineeInfoMapper.insert(info);
					}
				}
			}
			
			return returnMap;
			
		} catch(Exception e) {
			e.printStackTrace();
			returnMap.put("code", 500);
			returnMap.put("message", "文件上传失败");
			returnMap.put("data", null);
			
			return returnMap;
		}
	}

	@Override
	public void downloadQueBankFromCenter(Integer id) {
		Map<String, Object> params = new HashMap<String, Object>();
		
		try {
			
			String resultStr = HttpClientUtil.doGet(centerUrl + centerExamPaper + id);
			
		    GsonBuilder builder = new GsonBuilder();
		    
		    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
		    	@Override   
		    	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		    		return new Date(json.getAsJsonPrimitive().getAsLong()); 
		    	}
		    });
		    
		    // 同步试卷
		    ResultForQuestionBankList result = builder.create().fromJson(resultStr, ResultForQuestionBankList.class);
		    
			if (result.getCode() == 200) {
				List<QuestionBank> list = result.getData();
				OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				String filePath = paperPath + "/" + id;
				
				for (QuestionBank bank : list) {
					String key = bank.getPackageUrl();
					
					if (key != null && !"".equals(key)) {
						String allPath = filePath + "/" + bank.getId() + "/" + key;
						File file = new File(allPath);
						if (!file.getParentFile().exists()) {
							file.getParentFile().mkdirs();
							// file.createNewFile();
						}
						
						ossClient.getObject(new GetObjectRequest(bucket, key), file);
					}
			    }
				
				ossClient.shutdown();
			}
		    
			// 同步考试信息
			String examInfoStr = HttpClientUtil.doGet(centerUrl + centerExamItem + id);
			
			ResultForDeliveryExamInfo deliveryExamInfo = builder.create().fromJson(examInfoStr, ResultForDeliveryExamInfo.class);
		
			if (deliveryExamInfo.getCode() == 200) {
				DeliveryExamInfo examInfo = deliveryExamInfoMapper.selectByPrimaryKey(deliveryExamInfo.getData().getId());
				if (examInfo != null) {
					deliveryExamInfoMapper.updateByPrimaryKey(deliveryExamInfo.getData());
				} else {
					deliveryExamInfoMapper.insert(deliveryExamInfo.getData());
				}
			}
			
			// 同步所有试卷信息
			params.clear();
			params.put("organCode", uniquecode);
			String questionBankStr = HttpClientUtil.doPost(centerUrl + centerExamPaperAll, params);
			
			ResultForDeliveryQuestionBank banks = builder.create().fromJson(questionBankStr, ResultForDeliveryQuestionBank.class);
			
			if (banks.getCode() == 200) {
				List<DeliveryQuestionBank> list = banks.getData();
				for (DeliveryQuestionBank info : list) {
					DeliveryQuestionBank examineeInfo = deliveryQuestionBankMapper.selectByPrimaryKey(info.getId());
					if (examineeInfo != null) {
						deliveryQuestionBankMapper.updateByPrimaryKey(examineeInfo);
					} else {
						deliveryQuestionBankMapper.insert(info);
					}
				}
			}
			
			// 同步学校信息
			Map<String, String> organParams = new HashMap<String, String>();
			organParams.put("uniquecode", uniquecode);
			String sysOrganStr = HttpClientUtil.doGet(centerUrl + centerSysOrganInfoUrl, organParams);
			ResultForDeliverySysOrganization sysOrganData = builder.create().fromJson(sysOrganStr, ResultForDeliverySysOrganization.class);
			if (sysOrganData.getCode() == 200) {
				
				DeliverySysOrganization sysOrgan = deliverySysOrganizationMapper.selectByPrimaryKey(sysOrganData.getData().getId());
				if (sysOrgan != null) {
					deliverySysOrganizationMapper.updateByPrimaryKey(sysOrganData.getData());
				} else {
					deliverySysOrganizationMapper.insert(sysOrganData.getData());
				}
			}
			
		    System.out.println(resultStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Result syncExamScoresById(Integer id) {
		
		Result testConn = systemService.TestConn();
		if (testConn.getCode() == 200) {
			// 同步scores
			DeliveryExamineeScores scoreParam = new DeliveryExamineeScores();
			scoreParam.setExamInfoId(id);
			scoreParam.setField4(0);
			List<DeliveryExamineeScores> scores = deliveryExamineeScoresMapper.selectByParams(scoreParam);
			ExamineeScores scoreEntity = null;
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			
			for (DeliveryExamineeScores score : scores) {
				scoreEntity = new ExamineeScores();
				scoreEntity.setExamInfoId(score.getExamInfoId());
				scoreEntity.setqId(score.getqId());
				scoreEntity.setsNo(score.getsNo());
				scoreEntity.setsScore(score.getsScore());
				
				File file = new File(score.getqAnswerPath());
				if (file.exists()) {
					ossClient.putObject(bucket, file.getName(), file);
					scoreEntity.setqAnswerPath(file.getName());
				}
				
				Result result = examineeScoresService.syncScores(scoreEntity);
				
				if (result.getCode() == 200) {
					score.setField4(1);
					deliveryExamineeScoresMapper.updateByPrimaryKey(score);
				} else {
					return new Result(8106, "同步失败：学号" + score.getsNo() + "同步出错，请查看控制台信息");
				}
			}
			
			// 同步scores_detail
			DeliveryExamineeScoresDetail scoreDetailParam = new DeliveryExamineeScoresDetail();
			scoreDetailParam.setExamInfoId(id);
			scoreDetailParam.setField4(0);
			List<DeliveryExamineeScoresDetail> details = deliveryExamineeScoresDetailMapper.selectByParams(scoreDetailParam);
			DeliveryExamineeScoresDetail detailEntity = null;
			for (DeliveryExamineeScoresDetail detail : details) {
				detailEntity = new DeliveryExamineeScoresDetail();
				detailEntity.setExamInfoId(detail.getExamInfoId());
				detailEntity.setqExamineeAnswer(detail.getqExamineeAnswer());
				detailEntity.setqId(detail.getqId());
				detailEntity.setqStem(detail.getqStem());
				detailEntity.setqTopicScore(detail.getqTopicScore());
				detailEntity.setqType(detail.getqType());
				detailEntity.setqTypeClassify(detail.getqTypeClassify());
				detailEntity.setQueId(detail.getQueId());
				detailEntity.setQueNo(detail.getQueNo());
				detailEntity.setsNo(detail.getsNo());
				
				Result result = examineeScoresDetailService.syncScoreDetail(detailEntity);
				
				if (result.getCode() == 200) {
					detail.setField4(1);
					deliveryExamineeScoresDetailMapper.updateByPrimaryKey(detail);
				} else {
					return new Result(8106, "同步失败：学号" + detail.getsNo() + "同步出错，请查看控制台信息");
				}
			}
			
			// asyncTask.syncExamScores(id);
			return new Result(200, "同步考试成绩成功");
		} else {
			
			return new Result(8106, "请检查网络连接");
		}
	}
}
